<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2015 http://www.youdi365.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author:  心云间、凝听 <981248356@qq.com>
// +----------------------------------------------------------------------
namespace Admin\Controller;
use Common\Util\Tree;
use Admin\Builder\AdminFormBuilder;
use Admin\Builder\AdminListBuilder;
class AuthController extends AdminController {
    protected $authRuleModel;
    protected $authRoleModel;

    function _initialize()
    {
        parent::_initialize();
        $this->authRuleModel = D('auth_rule');
        $this->authRoleModel = D('auth_role');
    }
    //菜单管理(规则)
    public function rule(){
        $manage_type=isset($_GET['manage_type'])?$_GET['manage_type']:'menu';//管理类型
        // 获取所有节点信息
        $map['pid'] = I('get.pid/d',0);//是否存在父ID
        $paged=I('get.p/d',1);
        $map['is_menu']=1;//只显示菜单
        if ($map['pid']>0) {
            $current_submenu_name=M('auth_rule')->where(array('id'=>intval($map['pid'])))->getField('title');
            $meta_title=$current_submenu_name.'》子菜单管理';
        }else{
            $meta_title='菜单管理';
        }
        
        list($data_list,$totalCount) = $this->authRuleModel->getListByPage($map,$paged,'sort asc','*',20);
        foreach ($data_list as $key=>$list) {
            $data_list[$key]['p_menu']=M('auth_rule')->where(array('id'=>intval($list['pid'])))->getField('title');
        }
        $builder = new AdminListBuilder();
        $builder->setMetaTitle($meta_title)
            ->addTopButton('addnew',array('href'=>U('rule_edit',array('pid'=>$map['pid']))))  // 添加新增按钮
            ->addTopButton('resume',array('model'=>'auth_rule'))  // 添加启用按钮
            ->addTopButton('forbid',array('model'=>'auth_rule'))  // 添加禁用按钮
            ->addTopButton('delete',array('model'=>'auth_rule'))  // 添加删除按钮
            ->setSearch('', U('rule'))
            ->keyListItem('id','ID')
            ->keyListItem('title','名称','link',U('Auth/rule',array('pid'=>'__data_id__')))
            ->keyListItem('p_menu','上级菜单')
            ->keyListItem('name', 'URL')
            ->keyListItem('module', '模块')
            ->keyListItem('sort', '排序')
            ->keyListItem('status','状态','status')
            ->keyListItem('right_button', '操作', 'btn')
            ->setListDataKey('id')
            ->setListData($data_list)    // 数据列表
            ->setListPage($totalCount) // 数据列表分页
            ->addRightButton('edit',array('href'=>U('rule_edit',array('id'=>'__data_id__'))))      // 添加编辑按钮
            ->addRightButton('delete',array('model'=>'auth_rule'))// 添加删除按钮
            ->alterListData(
                array('key' => 'pid', 'value' =>'0'),
                array('p_menu' => '无'))
            ->display();
    }
    //菜单编辑
    public function rule_edit($id=0){
        $title=$id?"编辑":"新增";
        if ($id==0) {//新增
            $pid=I('get.pid/d');
            $pid_data =M('auth_rule')->find($pid);
            $menu_data=array('module'=>$pid_data['module'],'pid'=>$pid);
        }
        
        if(IS_POST){
            // 提交数据
            $data =$this->authRuleModel->create();
            if ($data) {
                $result =$this->authRuleModel->editData($data);
                if ($result) {
                    F('admin_menu',null);//清空后台菜单缓存
                    $this->success($title.'菜单成功', U('rule',array('pid'=>I('pid/d'))));
                } else {
                    $this->error($title.'失败', $this->authRuleModel->getError());
                }
            } else {
                $this->error($this->authRuleModel->getError());
            }
        }else{
            // 获取菜单数据
            if ($id!=0) {
                $menu_data =M('auth_rule')->find($id);
            }
            $menus = M('auth_rule')->field(true)->select();
            $menus = D('Common/Tree')->toFormatTree($menus,'title');

            $menus = array_merge(array(0=>array('id'=>0,'title_show'=>'顶级菜单')), $menus);
            $builder = new AdminFormBuilder();
            $builder->setMetaTitle($title.'菜单')  // 设置页面标题
                    ->addFormItem('id', 'hidden', 'ID', 'ID')
                    ->addFormItem('title', 'text', '标题', '用于后台显示的配置标题')
                    ->addFormItem('module', 'select', '所属模块', '所属的模块，模块菜单必须选择，否则无法导出',array('Admin'=>'后台模块','Home'=>'前台模块','User'=>'用户模块','Cms'=>'Cms模块'))
                    ->addFormItem('pid', 'multilayer_select', '上级菜单', '上级菜单',$menus);
            if ($menu_data['pid']==0) {
                $builder->addFormItem('icon', 'icon', '字体图标', '字体图标');
            }
            
            $builder->addFormItem('name', 'text', '链接', '链接')
                    //->addFormItem('show', 'select', '显示类型', '选择显示类型',array(1=>'是',0=>'否',2=>'开发者显示'))
                    ->addFormItem('sort', 'number', '排序', '排序')
                    ->setFormData($menu_data)
                    ->addButton('submit')->addButton('back')    // 设置表单按钮
                    ->display();
        }   
        
    }

    //角色管理
    public function role(){
        // 搜索
        $keyword   = I('keyword', '', 'string');
        $condition = array('like','%'.$keyword.'%');
        $map['title'] = array($condition);
        // 获取所有角色
        $map['status'] = array('egt', '0'); // 禁用和正常状态
        $paged=I('get.p/d',1);
        list($data_list,$totalCount) = $this->authRoleModel->getListByPage($map,$paged,'title desc','*',20);
        // 使用Builder快速建立列表页面。
        $builder = new AdminListBuilder();
        $builder->setMetaTitle('角色管理') // 设置页面标题
                ->addTopButton('addnew',array('href'=>U('role_add')))  // 添加新增按钮
                ->addTopButton('resume')  // 添加启用按钮
                ->addTopButton('forbid')  // 添加禁用按钮
                ->addTopButton('delete')  // 添加删除按钮
                ->setSearch('搜索角色')
                ->keyListItem('id', 'ID')
                ->keyListItem('title', '角色名')
                ->keyListItem('description', '描述')
                ->keyListItem('status', '状态','status')
                ->keyListItem('right_button', '操作', 'btn')
                ->setListData($data_list)    // 数据列表
                ->setListPage($totalCount,20) // 数据列表分页
                ->addRightButton('edit',array('href'=>U('role_edit',array('group_id'=>'__data_id__')))) 
                ->addRightButton('edit',array('title'=>'权限分配','href'=>U('access',array('group_id'=>'__data_id__'))))  
                ->addRightButton('edit',array('title'=>'成员授权','href'=>U('accessUser',array('group_id'=>'__data_id__'))))    
                ->display();
    }
	
	//创建角色
	public function role_add(){
        $this->meta_title ='添加角色';
        if (IS_POST) {
            $data = $this->authRoleModel->create();
            if ($data) {
                $id = $this->authRoleModel->add($data);
                if ($id) {
                    $this->success('添加角色成功', U('role'));
                } else {
                    $this->error('添加失败');
                }
            } else {
                $this->error($this->authRoleModel->getError());
            }
        } else {
            $this->display('role_edit');
        }
	}
	
    //角色编辑
    public function role_edit($group_id=0){
        $title=$group_id?'编辑':'新增';
        if ($group_id!=0) {
            $this->role_id=$group_id;
        }
        
        $this->meta_title =$title.'角色';
         $info =$this->authRoleModel->find($group_id);
         if (IS_POST) {
            $data['id']=$info['id'];
            $data['title']= I('post.title/s');
            $data['description']= I('post.description/s');
            if ($data) {
                $result = $this->authRoleModel->editData($data);
                if ($result) {
                    $this->success($title.'成功', U('role_edit'));
                } else {
                    $this->error($title.'失败');
                }
            } else {
                $this->error($this->authRoleModel->getError());
            }
        } else {
           
            $this->assign('info',$info);
            $this->display();
        }
    }
    //权限分配
    public function access($group_id=0){
        if ($group_id!=0) {
            $this->role_id=$group_id;
        }
        $title='权限分配';
        $this->meta_title =$title;
        if (IS_POST&&$group_id!=0) {
            $data['id']=$this->role_id;
            $menu_auth=isset($_POST['menu_auth'])?$_POST['menu_auth']:'';//获取所有授权菜单
            $data['rules']=implode(',',$menu_auth);
            if ($data) {
                $result = $this->authRoleModel->editData($data);
                if($group_id==1){
                    $this->error('管理员不能修改'.$title);
                }elseif ($result) {
                    F('admin_menu',null);
                    $this->success($title.'成功', U('role'));
                }else {
                    $this->error($title.'失败');
                }
            } else {
                $this->error($this->authRoleModel->getError());
            }
        }else{
            $role_auth_rule=$this->authRoleModel->where(array('id'=>intval($this->role_id)))->getField('rules');
            $this->assign('menu_auth_rules',explode(',',$role_auth_rule));//获取指定获取到的权限
        }
        $menu = M('auth_rule')->where(array('status'=>1,'pid'=>0))->order('sort asc')->select();
        foreach($menu as $k=>$v){
            $menu[$k]['_child']=M('auth_rule')->where(array('status'=>1,'pid'=>$v['id']))->order('sort asc')->select();
        }
        $this->assign('all_auth_rules',$menu);//所以规则
        $this->display();
    }
    /**
     * 用户组授权用户列表
     * @author 心云间、凝听 <981248356@qq.com>
     */
    public function accessUser($group_id=0)
    {
        if ($group_id!=0) {
            $this->role_id=$group_id;
        }

        $auth_group = M('AuthRole')->where( array('status'=>array('egt','0')))->getfield('id,id,title,rules');
        $_REQUEST = array();
        //$list = $this->lists($model,array('a.group_id'=>$group_id,'m.status'=>array('egt',0)),'m.uid asc',null,'m.uid,m.nickname,m.last_login_time,m.last_login_ip,m.status');
        $list= M('users m')->join ('__AUTH_ROLE_ACCESS__ a ON m.uid=a.uid' )->where(array('a.group_id'=>$group_id,'m.status'=>array('egt',0)))->order('m.uid asc')->field('m.uid,m.nickname,m.last_login_time,m.last_login_ip,m.status')->select();
        int_to_string($list);  
        $this->assign( '_list',     $list );
        $this->assign('auth_group', $auth_group);
        $this->assign('this_group', $auth_group[(int)$_GET['group_id']]);
        $this->meta_title = '成员授权';
        $this->display();
    }
    /**
     * 创建管理员用户组
     * @author 朱亚杰 <zhuyajie@topthink.net>
     */
    public function createGroup(){
        if ( empty($this->auth_group) ) {
            $this->assign('auth_group',array('title'=>null,'id'=>null,'description'=>null,'rules'=>null,));//排除notice信息
        }
        $this->meta_title = '新增用户组';
        $this->display('editgroup');
    }

    /**
     * 编辑管理员用户组
     * @author 朱亚杰 <zhuyajie@topthink.net>
     */
    public function editGroup(){
        $auth_group = M('AuthRole')->find( (int)$_GET['id'] );
        $this->assign('auth_group',$auth_group);
        $this->meta_title = '编辑用户组';
        $this->display();
    }

    /**
     * 管理员用户组数据写入/更新
     * @author 朱亚杰 <zhuyajie@topthink.net>
     */
    public function writeGroup(){
        if(isset($_POST['rules'])){
            sort($_POST['rules']);
            $_POST['rules']  = implode( ',' , array_unique($_POST['rules']));
        }
        $data = $this->authRoleModel->create();
        if ( $data ) {
            if ( empty($data['id']) ) {
                $r =$this->authRoleModel->add();
            }else{
                $r = $this->authRoleModel->save();
            }
            if($r===false){
                $this->error('操作失败'.$this->authRoleModel->getError());
            } else{
                $this->success('操作成功!',U('index'));
            }
        }else{
            $this->error('操作失败'.$this->authRoleModel->getError());
        }
    }
    /**
     * 修改用户组描述
     */
    public function descriptionGroup()
    {
        $title=$_POST['title'];
        $description=$_POST['description'];
        $id=$_POST['id'];
        $data['description']=$description;
        $data['title']=$title;
        $res=$this->authRoleModel->where('id='.$id)->save($data);
        if($res)
        {
            $this->success('修改成功!');
        }
        else{
            $this->error('修改失败!');
        }

    }
        /**
     * 将用户添加到用户组,入参uid,group_id
     * @author 朱亚杰 <zhuyajie@topthink.net>
     */
    public function addToGroup(){
        $uid = I('uid');
        $gid = I('group_id');
        if( empty($uid) ){
            $this->error('参数有误');
        }
        if(is_numeric($uid)){
            if ( is_administrator($uid) ) {
                $this->error('该用户为超级管理员');
            }
            if( !M('Users')->where(array('uid'=>$uid))->find() ){
                $this->error('管理员用户不存在');
            }
        }

        if( $gid && !$this->authRoleModel->checkGroupId($gid)){
            $this->error($this->authRoleModel->error);
        }
        if ( $this->authRoleModel->addToGroup($uid,$gid) ){
            $this->success('操作成功');
        }else{
            $this->error($this->authRoleModel->getError());
        }
    }

    /**
     * 将用户从用户组中移除  入参:uid,group_id
     * @author 朱亚杰 <zhuyajie@topthink.net>
     */
    public function removeFromGroup(){
        $uid = I('uid');
        $gid = I('group_id');
        if( $uid==UID ){
            $this->error('不允许解除自身授权');
        }
        if( empty($uid) || empty($gid) ){
            $this->error('参数有误');
        }
        if( !$this->authRoleModel->find($gid)){
            $this->error('用户组不存在');
        }
        if ( $this->authRoleModel->removeFromGroup($uid,$gid) ){
            $this->success('操作成功');
        }else{
            $this->error('操作失败');
        }
    }
    /**
     * 设置角色的状态
     */
    public function setStatus($model ='auth_rule'){
        $ids = I('request.ids');
        if (is_array($ids)) {
            if(in_array('1', $ids)) {
                $this->error('超级管理员不允许操作');
            }
        }else{
            if($ids === '1') {
                $this->error('超级管理员不允许操作');
            }
        }
        parent::setStatus($model);
    }
}